//
//  CZStatusDetailViewController.swift
//  GZWeibo007
//
//  Created by newuser on 15/12/24.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import SVPullToRefresh
import SVProgressHUD


// 统一管理cell的ID 
enum CZStatusDetailIdentifier: String {
    case DetailStatusNormalCell = "DetailStatusNormalCell"  // 原创cell的标识
    case DetailStatusForwardCell = "DetailStatusForwardCell"    // 转发cell标识
    case DetailNoDataCell = "DetailNoDataCell" ///没有评论
    case DetailCommentCell = "DetailCommentCell" ///<评论cell
    case DetailLoadingCell = "DetailLoadingCell"
    
   
//判断返回对应的cellID
    static func cellId(obj: AnyObject) -> String {
        if obj is CZStatus
        {
          return (obj as! CZStatus).retweeted_status == nil ? DetailStatusNormalCell.rawValue : DetailStatusForwardCell.rawValue
        }else if obj is CZDetailCommentModel {
        
        return (obj as! CZDetailCommentModel).loading ? DetailLoadingCell.rawValue : DetailCommentCell.rawValue
        }
       return DetailStatusNormalCell.rawValue
    }
}



class CZStatusDetailViewController: UIViewController {

    ///微博数据
    private var status: CZStatus
    
    ///微博模型
    private var comments: [CZDetailCommentModel] = [CZDetailCommentModel]()
    
    
    init(status: CZStatus) {
        self.status = status
        super.init(nibName: nil, bundle: nil)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        title = "微博详情"
        //准备UI
        prepareUI()
        
        //设置tableView
        prepareTableView()
        
        print("\(status.text)")

    }
    
    ///准备UI
    func prepareUI() {
    
        //添加子控制器
        view.addSubview(tableView)
        view .addSubview(bottomView)
        
        // 添加约束
        tableView.translatesAutoresizingMaskIntoConstraints = false
        bottomView.translatesAutoresizingMaskIntoConstraints = false
        
        // tableView水平
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb" : tableView]))
        
        // bottomView水平
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[bv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bv" : bottomView]))
        
        // 垂直方向
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[tb]-0-[bv(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb" : tableView, "bv": bottomView]))
        
    }
    
    
    ///设置tableView
    func prepareTableView() {
        
        //注册Cell
        tableView.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailStatusNormalCell.rawValue)
        tableView.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailStatusForwardCell.rawValue)
        tableView.registerClass(CZDetailNoDataCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailNoDataCell.rawValue)
        tableView.registerClass(CZDetailCommentCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailCommentCell.rawValue)
       tableView.registerClass(CZDetailLoadingCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailLoadingCell.rawValue)
        
        //设置代理数据源
        tableView.dataSource = self
        tableView.delegate = self
        
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            print("加载更多评论")
            self.loadMoreComment()
        }

        tableView.backgroundColor = UIColor(white: 0.9, alpha: 1)
        tableView.estimatedRowHeight = 200
    }
    
    
    
    
//MARK: - 懒加载控件
    ///tableView
    private lazy var tableView: UITableView = UITableView(frame: CGRectZero, style: UITableViewStyle.Plain)

    ///底部View
    private lazy var bottomView: CZStatusBottomView = {
      let view = CZStatusBottomView()
        //代理
      view.delegate = self
      return view
    }()
    
    //每个cell的头部view
    private lazy var detailHeaderView: CZDetailHeaderView = {
        let view = CZDetailHeaderView()
        //头部View代理方法
        view.delegate = self
        //数据传递过去
        view.status = self.status
        
        return view
    }()

}


// MARK: - 扩展实现多个代理
extension CZStatusDetailViewController: CZStatusCellDelegate,CZDetailHeaderViewDelegate,CZStatusBottomViewDelegate {
//MARK - 头部view代理方法
    func detailHeaderViewClick(headerView: UIView) {
        print("加载评论")
        loadNewComment()
    }
    
 ///加载评论
    func loadNewComment() {
    let since_id = comments.first?.id ?? 0
     //添加正在加载的数据cell
     let loadCommentModel = CZDetailCommentModel(loading: true)
        comments.insert(loadCommentModel, atIndex: 0)
        //重新刷新数据
        tableView.reloadData()
        // 滚动到第1组第0个cell
        tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1), atScrollPosition: UITableViewScrollPosition.Top, animated: false)
        //
    CZDetailCommentModel.loadComment(status.id, since_id: since_id, max_id: 0) { (comments, total_number, previous_cursor, next_cursor, error) -> () in
        
        //移除正在加载cell
        self.comments.removeFirst()
        if error != nil {
         print("加载最新评论失败: \(error)")
            SVProgressHUD.showErrorWithStatus("加载最新评论失败")
             self.tableView.reloadData()
            return
        }
         print("加载最新评论成功:\(comments?.count), next_cursor: \(next_cursor)")
        //显示评论数
        self.status.comments_count = total_number!
        
        //判断是否加载到数据
        if comments != nil && comments?.count > 0 {
            // 将新获取到的数据拼接在现有数据的前面
            self.comments = comments! + self.comments
        }
        self.tableView.reloadData()
      }
    }
///加载更多评论
    private func loadMoreComment() {
    
        CZDetailCommentModel.loadComment(status.id, since_id: 0, max_id: comments.last?.id ?? 0) { (comments, total_number, previous_cursor, next_cursor, error) -> () in
            // 停止上拉加载更多数据动画
            self.tableView.infiniteScrollingView.stopAnimating()
            if error != nil {
                SVProgressHUD.showErrorWithStatus("加载更多评论失败")
                print("\(error)")
                return
            }
            //下面表示有数据
            print("加载更多评论成功:\(comments?.count), next_cursor: \(next_cursor)")
            self.status.comments_count = total_number!
            self.tableView.showsVerticalScrollIndicator = next_cursor != 0
            if comments != nil  && comments?.count > 0 {
               self.comments += comments!
                self.tableView.reloadData()
            }
        }
    
    }
    

//转发cell点击
  func retweetStatusClick(clickStatus: CZStatus)
  {
     let detailVC = CZStatusDetailViewController(status: clickStatus)
     detailVC.hidesBottomBarWhenPushed = true
     navigationController?.pushViewController(detailVC, animated: true)
   }

///MARK: - 点赞评论模块代理方法
    func forwardButtonClick() {
        //点击跳转评论
       let forwardVC = CZGilmmerController(controllerType: CZComposeViewControllerType.Repost)
        forwardVC.status = status
       presentViewController(UINavigationController(rootViewController: forwardVC), animated: true, completion: nil)
    }
    func commentButtonClick() {
        
        let commentVC = CZGilmmerController(controllerType: CZComposeViewControllerType.Comment)
        commentVC.status = status
        presentViewController(UINavigationController(rootViewController: commentVC), animated: true, completion: nil)
        
    }
    func zanButtonClick() {
        SVProgressHUD.showErrorWithStatus("没有开放")
    }
    
}

///tabview数据源代理方法
extension CZStatusDetailViewController: UITableViewDataSource,UITableViewDelegate {

    //返回多少组
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    //每组有几个
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
        return 1
        
        }else {
            if comments.count == 0 {
              return 1
            }else {
                // 返回 评论数量
              return comments.count
            }
        
        }
    }
    
    //每行显示内容
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
          //获取id
            let cellId = CZStatusDetailIdentifier.cellId(status)
            
           let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! CZStatusCell
           
            cell.status = status
            //设置代理
            cell.cellDelegate = self
            
            return cell
            
        }else {
            if comments.count == 0
            {
           //获得id
            let cell = tableView.dequeueReusableCellWithIdentifier(CZStatusDetailIdentifier.DetailNoDataCell.rawValue) as! CZDetailNoDataCell
            cell.message = "还没有人评论"
            return cell
                
            }else {
               let commentModel = comments[indexPath.row]
                // 根据 重用标示 获取对应的cell
                let cellId = CZStatusDetailIdentifier.cellId(commentModel)
                let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! CZDetailCommentCell
                
              // 给cell设置 评论模型, cell根据 评论模型 显示 评论内容
                cell.model = commentModel
                return cell
            }
        }
        
        
    }
    
    
    //每行的行高
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        if indexPath.section == 0
        {
        
        //根据模型数据获得重用Cell
            let cellId = CZStatusDetailIdentifier.cellId(status)
            let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! CZStatusCell
            let height = cell.rowHeight(status)
            return height
        }else
        {
           return UITableViewAutomaticDimension
        }
    }

    //每组头部View
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?  {
        if section == 1 {
           
          return detailHeaderView
        }else {
          return nil
        }
    }

  /// tableView每组头部高度
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
          return 44
        }else {
         return 0
        }
    }
}




